from flask import Flask, render_template, request, jsonify
import json
import ai
import threading
from datetime import datetime
import core


app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')


@app.route('/chat', methods=['POST'])
def chat_api():
    message = request.json['message']
    try:
        response = ai.chat(message)
        return jsonify({'response': response})
    except Exception as e:
        return jsonify({'error': str(e)}), 500



@app.route('/get_history')
def get_history():
    try:
        # 使用绝对路径确保文件位置正确
        file_path = ai.MESSAGE_HISTORY_FILE
        with open(file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
            # print(data)
            # 统一返回格式并确保总是包含messages数组
            return jsonify({
                "messages": data.get('messages', []) if isinstance(data, dict) else data
            })
    except Exception as e:
        print(f"[HISTORY ERROR] {str(e)}")
        return jsonify({"messages": []})

@app.route('/reset_chat', methods=['POST'])
def reset_chat():
        try:
            ai.reset_history()
            return jsonify({'success': True})
        except Exception as e:
            print(f"[RESET ERROR] {str(e)}")
            return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/apply_code', methods=['POST'])
def apply_code():
    try:
        code = request.json['code']
        language = request.json['language']
        core.use_code_to_node(code)
        # 这里可以添加实际应用代码的逻辑
        print(f"Applying {language} code:\n{code}")
        # 添加调试日志
        with open('apply_code.log', 'a') as f:
            f.write(f"{language} code applied at {datetime.now()}\n")
            f.write(f"Code content:\n{code}\n\n")
        return jsonify({'success': True})
    except Exception as e:
        # 记录错误日志
        with open('apply_code_error.log', 'a') as f:
            f.write(f"Error at {datetime.now()}: {str(e)}\n")
        return jsonify({'success': False, 'message': str(e)}), 500



@app.after_request
def add_cors_headers(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
    return response

@app.route('/v1/services/opens/ips/format/json', methods=['GET'])
def get_client_ip():
    try:
        client_ip = request.headers.get('X-Forwarded-For', request.remote_addr)
        return jsonify({
            "status": "success",
            "data": {
                "ip": client_ip,
            }
        })
    except Exception as e:
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500



def run_app():
    app.run(host='0.0.0.0', port=8081, use_reloader=False)





def run_web_server():
    flask_thread = threading.Thread(target=run_app, daemon=True)
    flask_thread.start()




if __name__ == '__main__':
    run_app()
